const db = uniCloud.database();

exports.main = async (event, context) => {
  const { data = {} } = event;
  const { dishes = [], remarks = '' } = data;
  
  // 获取用户信息
  let uid = context.auth && context.auth.uid;
  
  // 如果 context.auth 为空，尝试从 event 中获取 token 并手动验证
  if (!uid && event.uniIdToken) {
    try {
      const jwtToken = require('jsonwebtoken');
      const decoded = jwtToken.decode(event.uniIdToken);
      if (decoded && decoded.uid) {
        uid = decoded.uid;
      }
    } catch (err) {
      // token 解析失败，继续
    }
  }

  if (!uid) {
    return {
      code: 401,
      message: '未授权',
      data: null
    };
  }

  if (!dishes || dishes.length === 0) {
    return {
      code: 400,
      message: '菜品为空',
      data: null
    };
  }

  try {
    const now = new Date();
    const orderNo = `ORD${now.getTime()}`;
    
    // 创建订单
    const result = await db.collection('food-order').add({
      order_no: orderNo,
      user_id: uid,
      dishes,
      remarks,
      status: 0, // 0=待处理、1=已接单、2=制作中、3=已完成
      status_time: {
        created: now
      },
      create_date: now,
      update_date: now
    });

    // 新 API：使用 result.id 获取插入的文档 ID
    const orderId = result.id || (result.ids && result.ids[0]);

    return {
      code: 200,
      message: '订单创建成功',
      data: {
        order_id: orderId,
        order_no: orderNo
      }
    };
  } catch (err) {
    return {
      code: 500,
      message: err.message,
      data: null
    };
  }
};
